/* 文章操作类
 * @Author: Leil 
 * @Date: 2018-08-24 16:59:49 
 * @Last Modified by: Leil
 * @Last Modified time: 2018-09-05 16:00:31
 */
const postModel = require('../models/post')

async function addOnePost(data) {
    console.log(data)
    let result = {}
    await postModel.addOnePost(data)
        .then(() => {
            result.info = '提交成功!'
        })
        .catch(error => {
            result.info = '提交失败!'
            result.error = error.errmsg
        })
    return result
}

async function getPosts() {
    let data = {}
    await postModel.getPosts()
        .then(posts => {
            data = posts
        })
        .catch(error => console.log(error))
    // console.log(data)
    return data
}

async function getPostById(postId) {
    let post = {}
    await postModel.getPostById(postId)
        .then(data => post = data)
        .catch(error => console.log(error.errmsg))
    return post
}

// 根据id更新文章
async function updatePostById(postId, data) {
    let result = {}
    await postModel.updatePostById(postId, data)
        .then(() => {
            result.info = '更新成功!'
        })
        .catch(error => {
            console.log(error.errmsg)
            result.error = error.errmsg
            result.info = '更新失败!'
        })
    return result
}

async function getPostsCountByCategoryId(categoryId) {
    let count = 0
    await postModel.getPostsCount({categoryId: categoryId})
            .then(res => {
                // console.log(res)
                count = res
            })
            .catch(error => {
                console.log(error.errmsg)
            })
    return count
}

async function getPostsByCategoryId(categoryId) {
    await postModel.getPostsByCondition({categoryId: categoryId})
            .then(res => {
                console.log(res)
            })
}

module.exports = {
    addOnePost,
    getPosts,
    updatePostById,
    getPostById,
    getPostsCountByCategoryId,
    getPostsByCategoryId
}